<template>
  <common-card title="今日订单" :value="numberFormat(orderToday)">
    <div ref="chartRef" style="width: 100%; height: 100%"></div>
    <template #bottom>
      <span>昨日订单量</span>
      <span class="emphasis">{{ numberFormat(orderLastDay) }}</span>
    </template>
  </common-card>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { useDataStore } from "@/stores/echartsData";
import useFormat from "@/hooks/useFormat";
import { $echarts } from "@/plugins/chart";
// 引入 echarts类型
import type { EChartsType } from "echarts";
// 实例化仓库
const dataStore = useDataStore();

const orderToday = ref<number>(0);
const orderLastDay = ref<number>(0);
const orderTrend = ref<number[]>([]);
const orderTrendAxis = ref<string[]>([]);

// 图表
const chartRef = ref();
// 初始阶段，不能确保找到DOM对象
let chart: EChartsType;

// 数据格式化
const { numberFormat } = useFormat();
// 对数据进行监控
watch(dataStore, (newVal) => {
  orderToday.value = newVal.reportData.orderToday as number;
  orderLastDay.value = newVal.reportData.orderLastDay as number;
  orderTrend.value = newVal.reportData.orderTrend as number[];
  orderTrendAxis.value = newVal.reportData.orderTrendAxis as string[];

  chart.setOption({
    xAxis: {
      type: "category",
      boundaryGap: false, // 两侧不留空白
      data: orderTrendAxis.value,
    },
    yAxis: {
      show: false, // 不显示y轴
    },
    series: [
      {
        name: "实时订单数",
        data: orderTrend.value,
        smooth: true, // 光滑线条
        type: "line",
        // 线条样式
        lineStyle: {
          opacity: 0,
        },
        // 折点样式
        itemStyle: {
          opacity: 0,
        },
        // 区域样式
        // areaStyle: {
        //   color: "skyblue",
        // },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "#83bff6", // 0% 处的颜色
              },
              {
                offset: 0.5,
                color: "#188df0", // 50% 处的颜色
              },
              {
                offset: 1,
                color: "#188df0", // 100% 处的颜色
              },
            ],
            global: false, // 缺省为 false
          },
        },
      },
    ],
    // 图表在坐标中显示位置
    grid: {
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
    },
    // 提示
    tooltip: {
      trigger: "axis",
    },
    color: ["skyblue"],
  });
});

onMounted(() => {
  // 初始化 页面加载完成，可以找到DOM元素
  chart = $echarts.init(chartRef.value);
  // 监听窗口变化
  window.addEventListener("resize", () => {
    // 窗口发生改变，图表自适应
    chart && chart.resize();
  });
});
</script>
<script lang="ts">
export default {
  name: "TodayOrder",
};
</script>

<style scoped></style>
